<template>
  <div>
    <!-- 顶部的部分 -->
    <div id="samplesFixed" :class="{'samples-fixed' : isFixed}">
      <el-row class="samples-info-box insert-page">
        <el-col :span="15">
          <h2>编辑合同</h2>
        </el-col>
        <!-- 右半边按钮区域 -->
        <el-col :span="9" class="samples-text-right">
          <el-button v-if="decodeURIComponent($route.query.status)=='草稿'" size="mini" plain type="success" @click="submitForm('ruleForm','save')">暂 存</el-button>
          <el-button size="mini" type="primary" plain @click="cancel">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </el-col>
      </el-row>
    </div>
    <el-row>
      <el-form ref="ruleForm" :model="ruleForm" class="samples-form" :rules="rules" label-width="140px">
        <div class="samples-info-box samples-pageForm">
          <span class="title">基本信息</span>
          <el-row class="samples-dialog-form">
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同分类：" prop="classifyId">
                <el-select v-model="ruleForm.classifyId" clearable style="width:100%" placeholder="请选择合同分类" size="small" @change="selectClassifyName" @clear="clearClassifyName">
                  <el-option
                    v-for="item in classifyNameList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同类型：" prop="typeId">
                <el-select v-model="ruleForm.typeId" clearable style="width:100%" placeholder="请选择合同类型" size="small" @change="selectTypeName" @clear="clearTypeName">
                  <el-option
                    v-for="item in typeNameList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>

            <el-col :lg="12" :xl="8">
              <el-form-item label="合同编号：" prop="code">
                <el-input v-model="ruleForm.code" clearable placeholder="请输入合同编号" size="small" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同名称：" prop="name">
                <el-input v-model="ruleForm.name" clearable placeholder="请输入合同名称" size="small" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>

            <el-col v-if="ruleForm.classifyId == &quot;001202&quot;" :lg="12" :xl="8">
              <el-form-item label="项目名称：" prop="projectName">
                <el-input v-model="ruleForm.projectName" clearable placeholder="请输入项目名称" size="small" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item prop="partyAId" label="甲方名称：">

                <el-select
                  v-model="ruleForm.partyAId"
                  filterable
                  remote
                  clearable
                  style="width: 100%;"
                  size="small"
                  class="samples-must-declared"
                  placeholder="请输入甲方名称"
                  :remote-method="querySearch"
                  popper-class="select-dropdown-width"
                  @change="getSelectPartyANameList"
                >
                  <el-option
                    v-for="item in partyANameList_temp"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>

            <el-col :lg="12" :xl="8">
              <el-form-item clearable prop="partyBId" label="乙方名称：">
                <el-select
                  v-model="ruleForm.partyBId"
                  filterable
                  remote
                  style="width: 100%;"
                  class="inline-input"
                  size="small"
                  clearable
                  placeholder="请输入乙方名称"
                  :remote-method="querySearchTwo"
                  popper-class="select-dropdown-width"
                  @change="getSelectPartyBNameList"
                >
                  <el-option
                    v-for="item in partyBNameList_temp"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
                <!-- <el-autocomplete
                  v-model="ruleForm.partyBName"
                  style='width: 100%;'
                  class="inline-input"
                  :fetch-suggestions="querySearchTwo"
                  placeholder="请输入乙方名称"
                  :trigger-on-focus="false"
                  clearable
                  size="small"
                  @select="handleSelectTwo"
                /> -->
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="业务单元：" prop="businessUnitId">
                <el-select
                  v-model="ruleForm.businessUnitId"
                  style="width: 100%;"
                  size="small"
                  clearable
                  placeholder="请选择业务单元"
                >
                  <el-option
                    v-for="item in unitList"
                    :key="item.deptId"
                    :label="item.name"
                    :value="item.deptId"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="合同金额：" prop="amount">
                <el-popover
                  ref="popover1"
                  popper-class="samples-input-popper-class"
                  placement="top"
                  trigger="focus"
                  :content="value11"
                />
                <el-input v-model="ruleForm.amount" v-popover:popover1 size="small" placeholder="请输入合同金额" clearable :change="fmoney1(ruleForm.amount)" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :xl="8">
              <el-form-item label="签约时间：" prop="signedTime">
                <el-date-picker
                  v-model="ruleForm.signedTime"
                  type="date"
                  style="width:100%"
                  value-format="yyyy-MM-dd"
                  size="small"
                  placeholder="选择签约时间"
                  clearable
                />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
            <!-- <el-col :lg="12" :xl="8">
              <el-form-item label="合同状态：" prop="status">
                <el-select v-model="ruleForm.status" clearable placeholder="请选择合同状态" style="width:100%" size="small">
                  <el-option
                    v-for="item in statusNameList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :lg="24" :xl="{span: 16, offset: 1,pull:1}">
              <el-form-item label="合同内容：" prop="content">
                <el-input v-model="ruleForm.content" clearable type="textarea" maxlength="500" resize="none" size="small" :autosize="{ minRows: 4, maxRows: 10}" placeholder="请输入合同内容" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div v-show="Lists.length > 0" class="samples-info-box  samples-pageForm" style="margin-bottom: 10px;">
          <span class="title">附件信息</span>
          <div class="tab-upload-box" style="margin-top: 15px;">
            <el-tabs class="samples-tabs">
              <el-tab-pane v-for="(item , index) in Lists" :key="index">
                <div slot="label" class="tabs-lable">
                  <span>{{ item.name }}</span>
                  <span>({{ fileList[index]?fileList[index].length:0 }})</span>
                </div>
                <upload
                  :multiple="false"
                  :action="action"
                  :file-list="fileList[index]"
                  @removeList="(i)=>{return spliceList(i,index)}"
                  @changeFile="files=>{return changeFileHandler(files,index)}"
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <div v-if="isCanMateriel" class="samples-info-box samples-pageForm">
          <el-row style="margin-bottom: 15px;">
            <el-col :span="15">
              <span class="title">物料信息</span>
            </el-col>
            <el-col :span="9" class="samples-text-right">
              <el-button size="mini" type="primary" plain @click="addMatrial">添加物料</el-button>
            </el-col>
          </el-row>
          <el-row class="samples-dialog-form">
            <el-form ref="tableForm" :model="materielTable" :rules="formRules" class="samples-dialog-form">
              <el-table :data="materielTable.data" class="contract-materiel" style="width: 100%">

                <el-table-column label="物料名称" width="200" fixed="left">
                  <template slot-scope="scope">
                    <el-form-item :rules="formRules.materielMust" label-width="0" :prop="`data[${scope.$index}].name`" class="samples-mb-75">
                      <el-input v-model="scope.row.name" placeholder="物料名称" clearable class="materielTable-input" />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="specification" label="规格" width="200">
                  <template slot-scope="scope">
                    <el-form-item :rules="formRules.materielMust" label-width="0" :prop="`data[${scope.$index}].specification`" class="samples-mb-75">
                      <el-input v-model="scope.row.specification" placeholder="规格" clearable class="materielTable-input" />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>

                  </template>
                </el-table-column>
                <el-table-column prop="brand" label="品牌" width="200">
                  <template slot-scope="scope">
                    <el-form-item :rules="formRules.materielMust" label-width="0" :prop="`data[${scope.$index}].brand`" class="samples-mb-75">
                      <el-input v-model="scope.row.brand" placeholder="品牌" clearable class="materielTable-input" />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>

                  </template>
                </el-table-column>
                <el-table-column prop="unitId" label="物料单位" width="200">
                  <template slot-scope="scope">
                    <el-form-item :rules="formRules.materielMustUnitId" label-width="0" :prop="`data[${scope.$index}].unitId`" class="samples-mb-75">
                      <el-select v-model="scope.row.unitId" filterable clearable style="width:100%" placeholder="物料单位" size="small" class="materielTable-input">
                        <el-option v-for="item in materielNameList" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>

                  </template>
                </el-table-column>

                <el-table-column label="物料单价" width="200">
                  <template slot-scope="scope">
                    <el-form-item :rules="formRules.priceNumber" label-width="0" :prop="`data[${scope.$index}].price`" class="samples-mb-75">
                      <el-input v-model="scope.row.price" clearable class="materielTable-input" placeholder="物料单价" @input="changeTotal(scope,scope.row.price,scope.row.number)" />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="物料数量" width="200">
                  <template slot-scope="scope">
                    <el-form-item :rules="formRules.priceNumber" label-width="0" :prop="`data[${scope.$index}].number`" class="samples-mb-75">
                      <el-input v-model="scope.row.number" clearable class="materielTable-input" placeholder="物料数量" @input="changeTotal(scope,scope.row.price,scope.row.number)" />
                      <template slot="error" slot-scope="scope">
                        <div class="sample-error-message">{{ scope.error }}</div>
                      </template>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="total" label="物料总价" width="200">
                  <template slot-scope="scope">
                    <span>{{ scope.row.total }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="操作" width="120" fixed="right">
                  <template slot-scope="scope">
                    <el-popover placement="left" trigger="click" popper-class="s-popover" width="234">
                      <div style="display:flex;align-items:center;justify-content:center;padding:20px 0;">
                        <i class="el-icon-question" style="font-size:26px;margin-right:10px;color:#e05e5e" /> 确定删除这条数据吗？
                      </div>
                      <div style="text-align: center; margin: 0">
                        <el-button size="small" type="primary" plain @click="handleClosePopover()">
                          取 消
                        </el-button>
                        <el-button type="primary" size="small" @click="deleteMatrial(scope.row,scope.$index)">
                          确 认
                        </el-button>
                      </div>
                      <el-button slot="reference" type="text" style="padding-top: 0;" class="samples-text-button-disabled">删 除</el-button>
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <div class="totalPriceRow">
              合计金额：{{ totalPrice }}
            </div>

          </el-row>
        </div>
      </el-form>
    </el-row>

  </div>
</template>

<script>
import sTable from '@/components/STable/s-table'
import {
  insertApi,
  queryUnit,
  selectContractApi,
  selectContractTableApi,
  selectMaterialTableApi,
  materialTableApi,
  deleteApi,
  detailApi,
  editApi,
  materialApi,
  getListApi,
  searchJiaYiApi,
  getContractStatusApi,
  operateApi,
  contractMagDictApi,
  getFileTagsApi,
  searchJiaYiNextApi,
  materialEditPageApi
} from '@/api/contractManage/contractMag'
import upload from '@/components/Supload/upload'
import { cacheMixin } from '@/utils/mixins/clearCache'

import {
  fixedMixin
} from '@/utils/mixins/fixedHeaderMixin'
import axios from 'axios'
import * as rulejs from '@/utils/rules'
var reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/
var numberDittContract = (rule, value, callback) => {
  const reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/
  if (value == '') {
    callback(new Error('请输入'))
  } else if (!reg.test(value) && value != null && value != '') {
    callback(new Error('请输入纯数字，支持小数点后四位'))
  } else {
    callback()
  }
}
var numberDittContractSave = (rule, value, callback) => {
  const reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/
  if (!reg.test(value) && value != null && value != '') {
    callback(new Error('请输入纯数字，支持小数点后四位'))
  } else {
    callback()
  }
}

export default {
  components: {
    upload,
    sTable
  },
  mixins: [cacheMixin, fixedMixin],
  data() {
    return {
      value11: '',
      formRules: {
        materielMust: [{ required: true, message: '请输入', trigger: 'blur' }],
        priceNumber: [{ required: true, message: '请输入', trigger: 'blur' }, { validator: numberDittContract, trigger: 'blur' }],
        materielMustUnitId: [{ required: true, message: '请选择', trigger: 'change' }]

      },
      unitNameList: '',
      establishTime: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
        }
      },
      isCanMateriel: false,
      partyANameList: [],
      partyBNameList: [],
      partyANameList_temp: [],
      partyBNameList_temp: [],
      fileList: [],
      totalPrice: 0,
      Lists: [],
      materielNameList: [],
      total: 0, // 分页
      ismore: false,
      multipleSelection: [],
      contractSearch: {
        code: '',
        name: '',
        unitName: '',
        beginTime: '',
        endTime: '',
        page: 1,
        pageSize: 10,
        classifyId: ''

      },
      materielTableVis: false,
      isFixed: false,
      materielTable: {
        data: []
      },
      unitList: [],
      classifyNameList: [],
      typeNameList: [],
      // statusNameList: [
      //   { id: 10, name: '执行中' },
      //   { id: 20, name: '已归档' }
      // ],
      ruleForm: {
        materialAmount: 0,
        amount: 0,
        attachmentList: [], // 附件
        businessUnitName: '', // 业务单元名称
        chooseList: [], // 选择的合同id
        materialList: [], // 物料信息
        classifyName: '', // 业务单元名称
        typeName: '', // 合同类型名称
        partyAId: '', // 甲名称
        partyBId: '', // 乙名称
        // statusName:'',//状态名称
        //
        classifyId: '',
        typeId: '',
        code: '',
        name: '',
        projectName: '',
        partyAName: '',
        partyBName: '',
        businessUnitId: null,
        amount: '',
        signedTime: null,
        // status:'',
        content: ''
      },
      rules: {
        classifyId: [
          { required: true, message: '请选择合同分类', trigger: 'change' }
        ],
        typeId: [
          { required: true, message: '请选择合同类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        partyAId: [
          { required: true, message: '请输入甲方名称', trigger: 'blur' }
        ],
        partyBId: [
          { required: true, message: '请输入乙方名称', trigger: 'blur' }
        ],
        businessUnitId: [
          { required: true, message: '请选择业务单元', trigger: 'change' }
        ],
        signedTime: [
          { required: true, message: '请选择签约时间', trigger: 'change' }
        ],
        // status: [
        //   { required: true, message: '请选择合同状态', trigger: 'change' },
        // ],
        content: [
          {
            min: 0,
            max: 500,
            message: '不能超过500字符',
            trigger: 'blur'
          }
        ],
        amount: [
          { required: true, message: '请输入合同金额', trigger: 'blur' },
          { validator: rulejs.numberMoney, trigger: 'blur' }
        ]

      },
      // status: [], // 企业经营状态
      action: '1'
    }
  },

  activated() {
    if (this.$route.query.isTag != true) {
      this.queryDetail()
    }
  },

  mounted() {
    this.queryDetail()
    contractMagDictApi('contract_classify').then(res => {
      this.classifyNameList = res.data
    })

    queryUnit().then(res => {
      this.unitList = res.data.data
    })
    materialApi().then(res => {
      if (res.code == 1) {
        this.materielNameList = res.data.data
      } else {
        this.$notify({
          title: '警告',
          type: 'warning',
          message: '查询物料单位接口异常',
          duration: '3000'
        })
      }
    })
  },
  methods: {
    fmoney1(s) {
      if (s == null) {
        return false
      }
      s = s.toString()
      if (s != '' && typeof (s) === 'string') {
        this.value11 = s.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      } else {
        this.value11 = ''
      }
    },
    queryDetail() {
      detailApi({ id: this.$route.query.id }).then(res => {
        if (res.code == 1) {
          this.ruleForm = Object.assign({}, this.ruleForm, res.data.contract)
          if (this.ruleForm.partyAId || this.ruleForm.partyAId == 0) {
            this.partyANameList_temp[0] = this.partyANameList[0] = { companyId: this.ruleForm.partyAId, companyName: this.ruleForm.partyAName }
          }
          if (this.ruleForm.partyBId || this.ruleForm.partyBId == 0) {
            this.partyBNameList_temp[0] = this.partyBNameList[0] = { companyId: this.ruleForm.partyBId, companyName: this.ruleForm.partyBName }
          }

          this.selectClassifyName('init')// 获取typeNameList
          // this.selectTypeName('init')
          if (this.ruleForm.typeId == '001301' || this.ruleForm.typeId == '001302' ||
                this.ruleForm.typeId == '001304' || this.ruleForm.typeId == '001401' ||
                this.ruleForm.typeId == '001402') {
            this.isCanMateriel = true
          }// 显示物料信息

          this.ruleForm.materialAmount ? this.totalPrice = (Number(this.ruleForm.materialAmount).toFixed(2) + '').replace(
            /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
            '$&,'
          ) : this.totalPrice = 0
          this.resetFMaterialiList()// 格式化物料
          if (!this.ruleForm.classifyName || !this.ruleForm.typeName) return
          getFileTagsApi({ classifyName: this.ruleForm.classifyName, typeName: this.ruleForm.typeName }).then(res2 => { // 查询Lists
            if (res2.code == 1) {
              this.Lists = res2.data
              this.fileList = []
              let startIndex = 0

              if (this.Lists.length > 0) {
                this.Lists.some((item, index) => {
                  res.data.attachmentList.some((item2, index2) => {
                    if (index2 > startIndex - 1) {
                      if (item.name == item2.typeItemName) {
                        this.fileList[index] == undefined ? this.fileList[index] = [] : true
                        item2.fileUrl = item2.fileId
                        item2.name = item2.fileName
                        item2.percentage = 100
                        this.fileList[index].push(item2)
                      } else {
                        startIndex = index2
                        return true
                      }
                    } else {
                      return false
                    }
                  })
                })
              }
            } else {
              this.$notify({
                title: '警告',
                type: 'warning',
                message: res2.msg,
                duration: '3000'
              })
            }
          })
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    resetFMaterialiList() {
      materialEditPageApi({ id: this.$route.query.id }).then(res => {
        if (res.code == 1) {
          this.materielTable.data = res.data
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    getSelectPartyANameList() {
      this.partyANameList = this.partyANameList_temp
    },
    getSelectPartyBNameList() {
      this.partyBNameList = this.partyBNameList_temp
    },
    clearClassifyName() {
      this.typeNameList = []
      this.ruleForm.typeId = null
    },
    selectClassifyName(init) {
      if (this.ruleForm.classifyId == '001201') {
        contractMagDictApi('single_contract_type').then(res => {
          this.typeNameList = res.data
        })
      } else if (this.ruleForm.classifyId == '001202') {
        contractMagDictApi('project_contract_type').then(res => {
          this.typeNameList = res.data
        })
      }
      if (init == 'init') return
      this.ruleForm.typeId = null
    },
    clearTypeName() {
      this.contractTable = []
      this.Lists = []
      this.fileList = []
    },
    selectTypeName(init) {
      this.contractTable = []// 清空合同信息
      this.fileList = []// 清空文件
      this.Lists = []// 清空文件tag信息
      if (this.ruleForm.typeId == null) {
        this.isCanMateriel = false
        this.materielTable.data = [{
          name: '',
          specification: '',
          brand: '',
          unitId: '',
          price: '',
          number: '',
          total: ''
        }]
        return
      }
      if (this.ruleForm.typeId == '001301' || this.ruleForm.typeId == '001302' ||
      this.ruleForm.typeId == '001304' || this.ruleForm.typeId == '001401' ||
      this.ruleForm.typeId == '001402') {
        this.isCanMateriel = true
      } else {
        this.isCanMateriel = false
      }

      this.classifyNameList.forEach(item => {
        if (item.code == this.ruleForm.classifyId) {
          this.ruleForm.classifyName = item.name
        }
      })

      this.typeNameList.forEach(item => {
        if (item.code == this.ruleForm.typeId) {
          this.ruleForm.typeName = item.name
        }
      })

      //   if(init == 'init') return
      getFileTagsApi({ classifyName: this.ruleForm.classifyName, typeName: this.ruleForm.typeName }).then(res => {
        if (res.code == 1) {
          this.Lists = res.data
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    changeTotal(scope, price, mount) {
      let priceError, numberError
      this.$refs['tableForm'].validateField(`data[${scope.$index}].price`, (valid) => {
        priceError = valid
      })
      this.$refs['tableForm'].validateField(`data[${scope.$index}].number`, (valid) => {
        numberError = valid
      })
      if (numberError || priceError) {
        scope.row.total = ''
        this.computeTotle()
        return
      }
      if (price && mount) {
        if (!reg.test(price) || !reg.test(mount)) {
          scope.row.total = ''
          this.computeTotle()
          return
        }
        scope.row.total = this.toThousands((price * mount).toFixed(2))
        this.computeTotle()
      } else {
        scope.row.total = ''
        this.computeTotle()
      }
    },
    computeTotle() {
      // const reg = /((^[1-9]\d*)|^0)(\.\d{0,4}){0,1}$/
      this.totalPrice = 0
      this.materielTable.data.forEach(item => {
        if (item.total) {
          this.totalPrice = this.toThousands((Number((this.totalPrice + '').replace(RegExp(',', 'g'), '')) + Number((item.total + '').replace(RegExp(',', 'g'), ''))).toFixed(2))
        }
      })
    },
    toThousands(num) {
      let mount = num.split('.')[0]
      const temp = mount.length % 3
      switch (temp) {
        case 1:
          mount = '00' + mount
          break
        case 2:
          mount = '0' + mount
          break
      }
      return mount.match(/\d{3}/g).join(',').replace(/^0+/, '') + '.' + num.split('.')[1]
    },
    addMatrial() {
      this.materielTable.data.push(
        {
          name: '',
          specification: '',
          brand: '',
          unitId: '',
          price: '',
          number: '',
          total: ''
        }

      )
    },
    deleteMatrial(row, index) {
      this.materielTable.data.splice(index, 1)
      this.computeTotle()
      this.handleClosePopover()
    },
    handleClosePopover() {
      document.querySelector('#app').click()
    },
    moreClick() {
      this.ismore = !this.ismore
      const ref = this.$refs.contractSearch.$el
      if (this.ismore) {
        ref.style.height = ref.scrollHeight + 'px'
      } else {
        ref.style.height = '32px'
      }
    },

    searchContract() {
      this.contractSearch.page = 1
      this.getContractSearchList()
    },
    handleSizeChange(val) {
      this.contractSearch.pageSize = val
      this.contractSearch.page = 1
      this.getContractSearchList()
    },
    handleCurrentChange(val) {
      this.contractSearch.page = val
      this.getContractSearchList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    headerCellClass({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      if (column.type === 'index') {
        return 'indexTableHeaderStyle'
      } else if (column.type === 'selection') {
        return ''
      } else {
        return 'samples-header-cell'
      }
    },

    querySearch(queryString) {
      var query = {
        companyName: queryString
      }
      this.partyANameList_temp = []
      searchJiaYiApi(query).then(response => {
        this.partyANameList_temp = this.partyANameList_temp.concat(response.data.data)
      })
      searchJiaYiNextApi(query).then(response => {
        if (response.code == '1') {
          if (response.data.data) {
            this.partyANameList_temp = this.partyANameList_temp.concat(response.data.data)
          }
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },

    querySearchTwo(queryString) {
      var query = {
        companyName: queryString
      }

      this.partyBNameList_temp = []
      searchJiaYiApi(query).then(response => {
        this.partyBNameList_temp = this.partyBNameList_temp.concat(response.data.data)
      })
      searchJiaYiNextApi(query).then(response => {
        if (response.code == '1') {
          if (response.data.data) {
            this.partyBNameList_temp = this.partyBNameList_temp.concat(response.data.data)
          }
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    querySearchThree(queryString, cb) {
      var query = {
        companyName: queryString
      }
      this.unitNameList = []
      searchJiaYiApi(query).then(response => {
        this.unitNameList = this.unitNameList.concat(response.data.data)
      })
      searchJiaYiNextApi(query).then(response => {
        if (response.code == '1') {
          if (response.data.data) {
            this.unitNameList = this.unitNameList.concat(response.data.data)
          }
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    cancel() {
      this.clearCache('contractMag/edit')
      this.closeTag('/contractManage/contractMag')
    },
    resetSaveRules() {
      this.formRules = {
        materielMust: [{ required: true, message: '请输入', trigger: 'blur' }],
        priceNumber: [{ required: true, message: '请输入', trigger: 'blur' }, { validator: numberDittContract, trigger: 'blur' }],
        materielMustUnitId: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    },
    submitForm(ruleForm, save) {
      if (save == 'save') {
        if (this.isCanMateriel) {
          this.formRules = {

            materielMust: [{ required: false, message: '请输入', trigger: 'blur' }],
            priceNumber: [{ required: false, message: '请输入', trigger: 'blur' }, { validator: numberDittContractSave, trigger: 'blur' }],
            materielMustUnitId: [{ required: false, message: '请选择', trigger: 'change' }]

          }
          this.$nextTick(() => {
            this.$refs['tableForm'].validate(validTableForm => {
              if (validTableForm) {
                this.premitContract(ruleForm, save)
              } else {
                this.resetSaveRules()
              }
            })
          })
        } else {
          this.premitContract(ruleForm, save)
        }
      } else {
        this.$refs[ruleForm].validate(valid => {
          let isPass = true
          if (this.isCanMateriel) {
            this.$refs['tableForm'].validate(validTableForm => {
              if (!validTableForm) {
                isPass = false
              }
            })
          }
          if (valid && isPass) {
            this.premitContract(ruleForm, save)
          }
        })
      }
    },
    premitContract(ruleForm, save) {
      const request = Object.assign({}, request, this.ruleForm)
      let message
      if (save == 'save') {
        request.tempFlag = 0
        request.statusName = '草稿'
        request.status = 1
        message = '暂存成功'
      } else {
        request.tempFlag = 1
        request.statusName = '执行中'
        request.status = 10
        message = '编辑成功'
      }

      if (request.classifyId != 0 && !request.classifyId) {
        request.classifyName = ''
      }
      if ((request.typeId != 0 && !request.typeId) || !request.typeId) {
        request.typeName = ''
      }

      if (request.businessUnitId == 0 || request.businessUnitId) {
        this.unitList.forEach(item => {
          if (item.deptId == request.businessUnitId) {
            request.businessUnitName = item.name
          }
        })
      } else {
        request.businessUnitName = ''
      }

      request.materialAmount = String(this.totalPrice).replace(RegExp(',', 'g'), '')

      if (request.partyAId == 0 || request.partyAId) {
        this.partyANameList.forEach(item => {
          if (item.companyId == request.partyAId) {
            request.partyAName = item.companyName
          }
        })
      } else {
        request.partyAName = ''
      }

      if (request.partyBId == 0 || request.partyBId) {
        this.partyBNameList.forEach(item => {
          if (item.companyId == request.partyBId) {
            request.partyBName = item.companyName
          }
        })
      } else {
        request.partyBName = ''
      }

      // 附件整理格式
      request.attachmentList = []
      if (this.fileList.length > 0) {
        this.fileList.forEach((item, index) => {
          this.Lists.forEach((item2, index2) => {
            if (index == index2) {
              if (item != undefined) {
                item.forEach((item3, index3) => {
                  item3.typeItemId = item2.id
                  item3.typeItemName = item2.name
                  item3.fileId = item3.fileUrl
                  item3.fileName = item3.name
                  request.attachmentList.push(item3)
                })
              }
            }
          })
        })
      }

      // this.unitList.forEach(item => {
      //   if(item.id == request.businessUnitId){
      //       request.businessUnitName= item.name
      //   }
      // });

      // 物料整理格式
      this.materielNameList.forEach(item => {
        this.materielTable.data.forEach(item2 => {
          if (item.id == item2.unitId) {
            item2.unitName = item.name
          }
        })
      })

      request.materialList = []

      request.currency = '人民币'
      if (!request.signedTime)request.signedTime = null
      this.materielTable.data.forEach(item => {
        item.total = String(item.total).replace(RegExp(',', 'g'), '')
        if (!Object.values(item).every((valueItem) => {
          return valueItem == false
        })) {
          request.materialList.push(item)
        }
      })

      // this.statusNameList.forEach(item => {
      //   if(item.id == request.status){
      //       request.statusName= item.name
      //   }
      // });

      editApi(request).then(res => {
        if (res.code == 1) {
          this.$notify({
            title: '成功',
            message: message,
            type: 'success',
            duration: 2000
          })

          this.clearCache('contractMag/edit')
          this.closeTag('/contractManage/contractMag')
        } else {
          this.resetSaveRules()
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },

    changeFileHandler(files, index) {
      this.$set(this.fileList, index, files)
    },
    spliceList(i, index) {
      const filelist = JSON.parse(JSON.stringify(this.fileList[index]))

      filelist.splice(i, 1)

      this.$set(this.fileList, index, filelist)

      const files = []
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i] !== undefined) {
          for (let j = 0; j < this.fileList[i].length; j++) {
            const obj = {}
            this.fileList[i][j]
            obj.fileId = this.fileList[i][j].fileUrl
            obj.name = this.fileList[i][j].name
            obj.size = this.fileList[i][j].size
            // obj.type = this.Lists[i].nodeName
            // obj.companyId = this.editForm.id
            files.push(obj)
          }
        }
      }
      updateFile(files).then(res => {
        if (res.code == '0') {

          // this.getCustomerinfo(this.editForm.id);
        } else {
          this.$notify({
            title: '错误',
            type: 'error',
            message: res.msg
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.projectOneTitle{
  margin-bottom: 20px;
}
.totalPriceRow{
color: #606266;
    font-size: 14px;
    text-align: right;
    margin-top: 12px;
}

</style>
<style lang='scss'>

.select-dropdown-width{
  width:390px;
  left: 1478px;
}
</style>

